//
//  PlayViewController.m
//  Ting
//
//  Created by 安静的美男子 on 14/11/12.
//  Copyright (c) 2014年 安静的美男子. All rights reserved.
//

#import "PlayViewController.h"
#import "AudioStreamerManager.h"
#import <AVFoundation/AVFoundation.h>
#import <ShareSDK/ShareSDK.h>
//#import "AFDownloadRequestOperation.h"

//@"http://fdfs.xmcdn.com/group5/M03/7F/1B/wKgDtlRjmtbi2PFNAAoU2wRAHic064.mp3"
@interface PlayViewController ()<UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate,UIActionSheetDelegate>
@property(nonatomic, assign)BOOL flag;

@end

@implementation PlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.number = [_num integerValue];
    
    

    [self play];

    [self CreatView];
    [self PlayerAction];
    [self CreatTabbar];
    
 
    
}
-(void)CreatView
{
    self.imageView = [[UIImageView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:_imageView];
    [_imageView sd_setImageWithURL:[NSURL URLWithString:    [NSString stringWithFormat:@"%@",[[_DataSource objectAtIndex:_number] coverLarge]]] placeholderImage:[UIImage imageNamed:@"123.gif"]];
    
    
    
    UIVisualEffectView *maskingView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
//    maskingView.backgroundColor = [UIColor whiteColor];
    maskingView.frame = self.imageView.frame;
    maskingView.alpha = 1;
    [self.view addSubview:maskingView];
    
    self.Scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, 320, 568 * 3 /4)];
    [self.view addSubview:_Scroll];
    _Scroll.contentSize = CGSizeMake(320 * 2,568 * 3 /4);
    _Scroll.contentOffset = CGPointMake(320, 0);
    _Scroll.backgroundColor = [UIColor clearColor];
    _Scroll.pagingEnabled = YES;
    _Scroll.showsHorizontalScrollIndicator = NO;
    _Scroll.delegate = self;
    
    self.MainBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _MainBt.frame = CGRectMake( 320 +10, 50, 300 , 300);
    [_MainBt sd_setBackgroundImageWithURL:[NSURL URLWithString:    [NSString stringWithFormat:@"%@",[[_DataSource objectAtIndex:_number] coverLarge]]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
    _MainBt.layer.cornerRadius = 150;
    _MainBt.backgroundColor = [UIColor clearColor];
    _MainBt.clipsToBounds= YES;
    self.MainBt.layer.borderWidth = 1;
    self.MainBt.layer.borderColor =[[UIColor blackColor]CGColor];
    
    [_MainBt addTarget:self action:@selector(DownLoadAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(5, 30, 310,330 ) style:UITableViewStyleGrouped];
    _table.delegate = self;
    _table.dataSource = self;
    //设置无线模式
//    [_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //设置线的颜色
    [_table setSeparatorColor:[UIColor lightGrayColor]];
    _table.showsVerticalScrollIndicator = NO;
    _table.backgroundColor = [UIColor clearColor];
    
    self.page = [[UIPageControl alloc]initWithFrame:CGRectMake( 0, 30+ 350 + 50, 320, 30)];
    self.page.numberOfPages = 2;
    self.page.currentPage = 1;
    [self.view addSubview:_page];

    
    
    [self.Scroll addSubview:_table];
    
    
    self.name = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 220, 30)];
    self.name.font = [UIFont systemFontOfSize:13];
    self.name.textColor = [UIColor whiteColor];
    self.name.text = [[_DataSource objectAtIndex:_number] title];
    self.name.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:_name];
    
    
    
    [_Scroll addSubview:_MainBt];
    
    _slider = [[UISlider alloc]initWithFrame:CGRectMake(35, 450, 240, 40)];
    [_slider addTarget:self action:@selector(changeTime:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:_slider];
    
    _currentTimeLB = [[UILabel alloc]initWithFrame:CGRectMake(0, 450, 40, 40)];
    [self.view addSubview:_currentTimeLB];
    _currentTimeLB.font = [UIFont systemFontOfSize:10];
    
    _currentTimeLB.text = @"00:00";
    _timeLB = [[UILabel alloc]initWithFrame:CGRectMake(275, 450, 40, 40)];
    [self.view addSubview:_timeLB];
    _timeLB.font = [UIFont systemFontOfSize:10];

    _timeLB.text = @"00:00";
    
    self.playBT = [UIButton buttonWithType:UIButtonTypeCustom];
    _playBT.frame = CGRectMake(160 - 15, 500, 30, 30);
    
    [_playBT setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-6.png"] forState:UIControlStateNormal];
    [_playBT addTarget:self action:@selector(PlayerAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:_playBT];
    self.previous = [UIButton buttonWithType:UIButtonTypeCustom];
    self.previous.frame = CGRectMake(20, 500, 30, 30);
    [self.previous setBackgroundImage:[UIImage imageNamed: @"iconfont-ttpodicon.png"] forState:UIControlStateNormal];
    [self.previous addTarget:self action:@selector(previousAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_previous];
    self.next = [UIButton buttonWithType:UIButtonTypeCustom];
    self.next.frame = CGRectMake(250, 500, 30, 30);
    [self.next setBackgroundImage:[UIImage imageNamed: @"iconfont-ttpodicon-2.png"] forState:UIControlStateNormal];
     [self.next addTarget:self action:@selector(NextAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_next];

    
    
    [self CreatTabbar];
    


}

-(void)changeSlider
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    
    if (!audioManager.PLAYER || [[[_DataSource objectAtIndex:_number] playUrl32] isEqualToString:@"" ]) {
        self.slider.value = 0;
        return;
        
    }
    self.slider.minimumValue = 0;
    
    self.slider.maximumValue = 1;
    
    self.slider.value = CMTimeGetSeconds(audioManager.PLAYER.currentItem.currentTime)/CMTimeGetSeconds(audioManager.PLAYER.currentItem.duration);
    
    int currentTime = CMTimeGetSeconds(audioManager.PLAYER.currentItem.currentTime);
    
    _currentTimeLB.text = [self TimeforMatFromSeconds:currentTime];
    int time = CMTimeGetSeconds(audioManager.PLAYER.currentItem.duration);
    _timeLB.text = [self TimeforMatFromSeconds:time];
    //自动下一曲
    if (_DataSource.count != 0) {
        
    
    if (_slider.value == 1) {
        [self NextAction];
        
    }
    }
    //当前时间label的值等于[self  TimeformatFromSeconds:audioManager.strmemer.progress];
    
}
//计算总时间方法,带一个参数,参数就是进度条.slider

-(NSString *)TimeforMatFromSeconds:(int)seconds
{
//    int totalm = seconds / (60);
    int h= seconds/ (60) /(60);
    int m = seconds / (60);
    int s = seconds %(60);
    if (h == 0) {
        
        return [NSString stringWithFormat:@"%02d:%02d",m,s];
    }
    else
    {
    return [NSString stringWithFormat:@"%02d:%02d:%02d",h,m,s];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _page.currentPage = _Scroll.contentOffset.x / 320;
    
}
-(void)animan
{
    _MainBt.transform = CGAffineTransformRotate(_MainBt.transform,2 * M_PI / 60.0 /100);
}
-(void)play
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    if (_DataSource.count != 0) {
        
        [audioManager playWithData:_DataSource num:_number model:_DataSource[_number]];
    }
    
        

    

}
-(void)CreatTabbar
{
//    self.downView = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 50, [UIScreen mainScreen].bounds.size.width, 50)];
//    _downView.backgroundColor = [UIColor clearColor];
//    _downView.alpha = 0.4;
//    [self.view addSubview:_downView];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.frame = CGRectMake(280, 20, 30, 30);
    
    [self.backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.backButton setImage:[UIImage imageNamed:@"iconfont-xiangxiajiantou.png"] forState:UIControlStateNormal];
    [self.view addSubview:_backButton];
   
}
-(void)backAction
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
-(void)PlayerAction
{
    if (_flag) {
        
        [self.playBT setBackgroundImage:[UIImage imageNamed: @"iconfont-bofang-3.png"] forState:UIControlStateNormal];
        AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
        [audioManager pause];
        [_time invalidate];
        [_timer invalidate];
        _flag = !_flag;
        [audioManager setFlag:_flag];
        
    }else
    {
        [self.playBT setBackgroundImage:[UIImage imageNamed: @"iconfont-bofang-6.png"] forState:UIControlStateNormal];
        AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
        [audioManager.PLAYER play];
        _time =  [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(animan) userInfo:nil repeats:YES];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(changeSlider) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        _flag = !_flag;
        [audioManager setFlag:_flag];
        
        
    }

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _DataSource.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ind = @"liebiao";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ind];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ind];
        
    }
    cell.textLabel.text = [_DataSource[indexPath.row] title];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    //清灰~~~!!!!!!!
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    
    _number = indexPath.row;
    
    [audioManager playWithData:_DataSource num:indexPath.row model:_DataSource[indexPath.row]];
    
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:[_DataSource[indexPath.row] coverLarge]] placeholderImage:[UIImage imageNamed:@"123.gif"]];
    self.name.text = [_DataSource[indexPath.row] title];
    [self.MainBt sd_setBackgroundImageWithURL:[NSURL URLWithString:[_DataSource[indexPath.row] coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
    
}
-(void)previousAction
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    if (_number - 1 >= 0) {
        
        _number = _number - 1;
        [audioManager playWithData:_DataSource num:_number model:_DataSource[_number]];
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:[_DataSource[_number] coverLarge]] placeholderImage:[UIImage imageNamed:@"123.gif"]];
        self.name.text = [_DataSource[_number] title];
        [self.MainBt sd_setBackgroundImageWithURL:[NSURL URLWithString:[_DataSource[_number] coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
        

    }else
    {
        NSLog(@"到头了");
        
    }
    
   
}
-(void)NextAction
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    if (_number + 1 != _DataSource.count) {
        
        _number = _number + 1;
        [audioManager playWithData:_DataSource num:_number model:_DataSource[_number]];
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:[_DataSource[_number] coverLarge]] placeholderImage:[UIImage imageNamed:@"123.gif"]];
        self.name.text = [_DataSource[_number] title];
        [self.MainBt sd_setBackgroundImageWithURL:[NSURL URLWithString:[_DataSource[_number] coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
        
        
    }else
    {
        NSLog(@"到头了");
        _number = 0;
        [audioManager playWithData:_DataSource num:_number model:_DataSource[_number]];
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:[_DataSource[_number] coverLarge]] placeholderImage:[UIImage imageNamed:@"123.gif"]];
        self.name.text = [_DataSource[_number] title];
        [self.MainBt sd_setBackgroundImageWithURL:[NSURL URLWithString:[_DataSource[_number] coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
        
    }
    

}
-(void)changeTime:(UISlider *)sender
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
   
    int32_t time = audioManager.PLAYER.currentItem.asset.duration.timescale;
    Float64 TimeValue =CMTimeGetSeconds(audioManager.PLAYER.currentItem.duration) * sender.value ;
    
    [audioManager.PLAYER  seekToTime:CMTimeMakeWithSeconds(TimeValue, time) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    [audioManager.PLAYER play];
    
    //    sender.value = CMTimeGetSeconds(audioManager.PLAYER.currentItem.currentTime)/CMTimeGetSeconds(audioManager.PLAYER.currentItem.duration);
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [_time invalidate];
    [_timer invalidate];
    
}

-(void)DownLoadAction
{
    _actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:[NSString stringWithFormat:@"%@",[_DataSource[_number]title]]
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"分享当前",@"下载当前",nil];
    _actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [_actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (actionSheet == _actionSheet) {
        
    
    if (buttonIndex == 0) {
        
    
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK"  ofType:@"jpg"];
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@,Ting说有你,更加精彩%@",[_DataSource[_number] title],[_DataSource[_number]playUrl64]]
                                       defaultContent:@"默认分享内容，没内容时显示"
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"ShareSDK"
                                                  url:@"http://www.sharesdk.cn"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    [ShareSDK showShareActionSheet:nil
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions: nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(@"分享成功");
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_SHARE_FAI", @"发布失败!error code == %d, error code == %@"), [error errorCode], [error errorDescription]);
                                }
                            }];
    }
       else if (buttonIndex == 1) {
            
           DownLoadManager *manager = [DownLoadManager shareManager];
           
           [manager downloadWithBlock:^(BOOL have) {
               _have = have;
           } url:[ _DataSource[_number]downloadUrl]
                                 name:[ _DataSource[_number]title]];
           
           
           if (_have) {
               UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                              message:@"已经加入下载列表,请勿重复添加" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
               [alert show];

           }
           
           
           else{
           
           
           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                          message:@"已成功加入下载列表" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
           [alert show];
           
           
            
           }
           
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
